import axios from "axios";
import { showNotify } from "vant";
import { uesUserStore } from "@/stores/user";
import CryptoJS from "crypto-js";
import jsRsa from "@/utils/jsEncrypt";

enum MSGS {
  "操作成功" = 200,
  "请求异常",
}

const request = axios.create({
  // baseURL: '/mock',
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 200000,
  headers: {
    "Content-Type": "application/json;charset:utf-8",
  },
});

request.interceptors.request.use((config) => {
  config.headers = config.headers || {};

  const aesKey = CryptoJS.lib.WordArray.random(32).toString(
    CryptoJS.enc.Base64
  );
  config.aesKey = aesKey;

  let sessionKey = jsRsa
    .encrypt(aesKey)
    .replace(/\+/g, "-")
    .replace(/\//g, "_");

  if (uesUserStore().tokenGetter) {
    config.headers["Authorization"] = uesUserStore().tokenGetter;
  }
  config.headers.sessionKey = sessionKey;

  return config;
});

request.interceptors.response.use(
  (res) => {
    if (typeof res.data !== "object") {
      const aesKey = res.config.aesKey;

      let key = CryptoJS.enc.Base64.parse(aesKey);

      const decryptedContent = CryptoJS.AES.decrypt(res.data, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });

      let s = decryptedContent.toString(CryptoJS.enc.Utf8);
      res.data = JSON.parse(s);
    }

    const code: number = res.data.code;
    if (code === 200) {
      return res.data;
    } else {
      showNotify({ type: "danger", message: res.data.msg });
      return Promise.reject(res.data);
    }
  },
  (err) => {
    console.log("error", err);
  }
);

export default request;
